13. Placeholders
Placeholders can be constrained like any other view in a layout but the power in
them is that they can position existing objects.
If that object is already on screen, the placeholder position becomes
its new position and it is gone from the original location.
This allows you to do some basic templating and animations for cheap.
Consider this scenario, you might have a part of your UI that you might want to reuse across your app and have it contained in a merge tag like the following.
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:parentTag="android.support.constraint.ConstraintLayout">
<android.support.constraint.Placeholder
android:id="@+id/template_main_image"
// apply whatever constraints
/>
<!-- additional elements here -->
</merge>
In your app, you could dynamically replace the content of the Placeholder with the following code:
placeholder = (Placeholder) findViewById(R.id.template_image);
imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
TransitionManager.beginDelayedTransition(constraintLayout);
placeholder.setContentId(view.getId());
}
});
Note that despite many examples using merge, it is not required to use Placeholders.